#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import math

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class GansuJiuquanPolicy(BaseTaxPolicySpider):
    name = 'gansu_jiuquan_qu3_policy'
    
    province = '甘肃省'
    city: str = "酒泉市"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格
    page_size = 40

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOADER_MIDDLEWARES": {
                    # "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None,  # 为 None 失效
                    "scrapy.downloadermiddlewares.retry.RetryMiddleware": None,  # 为 None 失效
                    "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": 550,
                    "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": 551,
                    "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": 552,
                    'components.middlewares.downloadmiddlewares.private.rs_6_middlewares.Rs6RetryMiddleware': 553,
                },
                "DOWNLOAD_TIMEOUT": 200,
                # 'CONCURRENT_REQUESTS': 1,
                # "HTTPERROR_ALLOWED_CODES": [400, 404, 500, 200, 202, 502, 412],
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ["酒泉市肃北县人民政府", "肃北县", "https://www.subei.gov.cn/suBei/c111423/zfxxgk_zfwj.shtml"],
            ["酒泉市肃北县发展和改革局", "肃北县", "https://www.subei.gov.cn/suBei/c101309/xxgk_fzggj_list.shtml"],
            ["酒泉市肃北县工业和信息化局", "肃北县", "https://www.subei.gov.cn/suBei/c101331/xxgk_gxj_list.shtml"],
            # ["酒泉市肃北县民政局", "肃北县", "https://www.subei.gov.cn/suBei/c101353/xxgk_mzj_list.shtml"],
            ["酒泉市肃北县财政局", "肃北县", "https://www.subei.gov.cn/suBei/c101375/xxgk_czj_list.shtml"],
            # ["酒泉市肃北县人力资源和社会保障局", "肃北县", "https://www.subei.gov.cn/suBei/c101386/xxgk_rsj_list.shtml"],
            ["酒泉市阿克塞哈萨克族自治县人民政府", "阿克塞哈萨克族自治县", "https://www.akesai.gov.cn/akshskz/c111303/zfxxgk_zfwj.shtml"],
            ["酒泉市阿克塞哈萨克族自治县人民政府", "阿克塞哈萨克族自治县", "https://www.akesai.gov.cn/akshskz/c111304/zfxxgk_zfwj.shtml"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_content, meta={'item': item})

    def parse_content(self, response, **kwargs):
        meta = response.meta
        channelId = response.xpath('//meta[@name="channelId"]/@content').get()
        params = {
            "sort": "",
            "_isAgg": "false",
            "_isJson": "true",
            "_pageSize": f"{self.page_size}",
            "_template": "index",
            "_rangeTimeGte": "",
            "_rangeTimeLt": "",
            "_channelName": "",
            "page": "1"
        }
        url = '/common/search/' + channelId + '?'
        meta['params'] = params
        meta['url'] = url
        yield response.follow(url + urlencode(params), callback=self.parse_list, meta=meta)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        meta = response.meta
        datas = response.json()['data']

        for elem in datas['results']:
            item = Item()
            item['source_url'] = elem['url']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['publishedTimeStr'].split(" ")[0]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if 'htm' not in item['source_url'] and 'shtm' not in item['source_url']:
                print(elem['url'], elem['title'])
                item['title'] = elem['title']
                # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
                item['content'] = item['source_url']
                # item['source'] = self.source
                item['province'] = self.province
                item['city'] = self.city
                # item['county'] = self.county
                item['park'] = self.park
                yield item
            else:
                print(response.url, item['source_url'])
                yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total = datas['total']
            total_page = math.ceil(total / self.page_size)
            url = meta['url']
            params = meta['params']
            print(response.url, "page:", params['page'])
            params['page'] = int(params['page']) + 1
            if total_page < int(params['page']):
                return
            yield response.follow(url + urlencode(params), callback=self.parse_list, meta={'item': prev_item, 'url': url, 'params': params})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl gansu_jiuquan_qu3_policy".split())
